import { defineStore } from 'pinia';
import { ref } from 'vue';

export const useNutritionStore = defineStore('nutrition', () => {
  // 状态
  const meals = ref([]);
  const nutritionGoals = ref({
    calories: 2000,
    protein: 120,
    carbs: 250,
    fat: 65
  });

  // 从本地存储加载数据
  const loadMeals = (date) => {
    try {
      const dateStr = date.toISOString().split('T')[0];
      const savedMeals = localStorage.getItem(`meals_${dateStr}`);
      const savedGoals = localStorage.getItem('nutritionGoals');

      if (savedMeals) meals.value = JSON.parse(savedMeals);
      else meals.value = [];

      if (savedGoals) nutritionGoals.value = JSON.parse(savedGoals);
    } catch (error) {
      console.error('Failed to load nutrition data:', error);
      meals.value = [];
    }
  };

  // 保存数据到本地存储
  const saveMeals = (date) => {
    try {
      const dateStr = date.toISOString().split('T')[0];
      localStorage.setItem(`meals_${dateStr}`, JSON.stringify(meals.value));
      localStorage.setItem('nutritionGoals', JSON.stringify(nutritionGoals.value));
    } catch (error) {
      console.error('Failed to save nutrition data:', error);
    }
  };

  // 动作
  const addMeal = (meal) => {
    meals.value.push({
      id: Date.now(),
      ...meal
    });
    saveMeals(new Date(meal.date));
  };

  const deleteMeal = (meal) => {
    meals.value = meals.value.filter(m => m.id !== meal.id);
    saveMeals(new Date(meal.date));
  };

  const updateNutritionGoals = (goals) => {
    nutritionGoals.value = {
      ...nutritionGoals.value,
      ...goals
    };
    localStorage.setItem('nutritionGoals', JSON.stringify(nutritionGoals.value));
  };

  const clearDailyMeals = (date) => {
    const dateStr = date.toISOString().split('T')[0];
    meals.value = [];
    localStorage.removeItem(`meals_${dateStr}`);
  };

  return {
    meals,
    nutritionGoals,
    loadMeals,
    addMeal,
    deleteMeal,
    updateNutritionGoals,
    clearDailyMeals
  };
});